

import java.util.ArrayList;



public class MethodDecl {

	// ID
	String methodName;
	Type type;
	FormalParams formalParams;
	Block block;

	public MethodDecl(String methodName, Type type, FormalParams formalParams,
			Block block) {
		super();
		this.methodName = methodName;
		this.type = type;
		this.formalParams = formalParams;
		this.block = block;
	}

	public void checkDefinition() throws SemanticException {
		SymbolTable table = SymbolTable.getInstance();
		if (table.contains(methodName))
			throw new SemanticException("Identifier exists: " + methodName);
		Entry e = new Entry(methodName, Entry.METHOD, type.type);
		table.add(e);
		if (formalParams != null)
			e.paramsType = formalParams.getParamsList();
		else
			e.paramsType = new ArrayList<Integer>();
	}

	public void check() throws SemanticException {
		SymbolTable table = SymbolTable.getInstance();
		// checkDefinition();
		table.openScope();
		Entry e = table.get(methodName);
		table.setCurrentMethod(e);
		// System.out.println("checking method " + e.id);
		if (formalParams != null)
			formalParams.check();
		block.check();
		checkReturnStatement();
		table.closeScope();
	}

	public void checkReturnStatement() throws SemanticException {
		if (block == null)
			throw new SemanticException("There is no return statement");
		if (!block.hasReturnStatement())
			throw new SemanticException("There is no return statement");

	}

	public String toString() {
		String ret = "MethodDecl " + methodName + "\n";
		String s = "";
		if (formalParams != null) {
			s += formalParams.toString() + block.toString();
			for (String st : s.split("\n"))
				ret += "| " + st + "\n";
		}
		return ret;
	}
}
